import { reactive, ref, computed, onMounted } from '@shared'
import useTable from '@util/use/table'
import API from '@/api'
import confirm from '@/components/confirm'

// 1账号处于启用状态 2 账号处于禁用状态
const statusFormat2 = id => {
  switch (id) {
    case 1:
      return '启用'
    case 2:
      return '禁用'
    default:
      return null
  }
}

const useDialog = () => {
  const form = ref('null')
  const dialogLoading = ref(false)
  const visible = ref(false)
  const id = ref(null)
  const model = ref({
    name: '',
    phone: '',
    roles: [],
    adminType: false
  })

  const dialogTitle = computed(() => id.value !== null ? '编辑' : '添加')

  const fetchModelData = id => {
    dialogLoading.value = true
    API.user.get(id)
      .then(res => {
        // TODO: 获取用户详情并填充model
        model.value = {
          name: res.name,
          phone: res.phone,
          adminType: res.adminType,
          roles: res.roles.map(r => r.id)
        }
      })
      .catch(() => {
        visible.value = false
      })
      .finally(() => {
        dialogLoading.value = false
      })
  }

  const startEdit = (key = null) => {
    id.value = key
    if (key !== null) {
      // 编辑
      fetchModelData(key)
    }

    visible.value = true
  }

  const endEdit = () => {
    id.value = null

    form.value.resetFields()
  }

  const handleUpdate = async () => {
    const valid = await form.value.validate().catch(() => {})
    if (valid) {
      const isAdd = id.value === null
      const request = (id, params) => {
        return isAdd ? API.user.add(params) : API.user.update(id, params)
      }
      request(id, model.value)
        .then(() => {
          visible.value = false
        })
    }
  }

  return {
    form,
    dialogTitle,
    visible,
    dialogLoading,
    model,
    startEdit,
    endEdit,
    handleUpdate
  }
}

export default () => {
  const { table, reset, reload } = useTable()
  const { visible, startEdit, endEdit, dialogTitle, handleUpdate, model, form, dialogLoading } = useDialog()
  // 查询条件
  const search = reactive({
    name: ''
  })

  const options = reactive({
    role: []
  })

  const handleSearch = () => reset()

  const handleDelete = async id => {
    await confirm('提示', '确定要删除该用户？')
    API.user.delete(id)
      .then(() => reload())
  }
  // 切换禁用/启用
  const toggleStatus = ({ id, status }) => {
    const newStatus = status === 1 ? 2 : 1
    API.user.update(id, { status: newStatus })
      .then(() => reload())
  }

  const statusFormat = statusFormat2

  const fetchRoleList = () => {
    API.role.list().then(res => {
      const list = res.list || []
      options.role = list.map(r => ({ key: r.id, val: r.roleName }))
    })
  }
  onMounted(() => {
    fetchRoleList()
  })

  return {
    search,
    options,
    handleSearch,
    table,
    handleDelete,
    statusFormat,
    toggleStatus,
    // dialog
    form,
    visible,
    dialogLoading,
    model,
    dialogTitle,
    startEdit,
    endEdit,
    handleUpdate
  }
}
